<!DOCTYPE html><html lang="zh-CN" data-theme="dark"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>Golang结构体 | J.のblog</title><meta name="keywords" content="云原生,golang"><meta name="author" content="J."><meta name="copyright" content="J."><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#0d0d0d"><meta name="description" content="结构体Go语言的结构体有点像面向对象语言中的”类”，但不完全是，Go语言也没打算真正实现面向对象范式 定义使用type定义结构体，可以把结构体看做类型使用。必须指定结构体的字段（属性）名称和类型。 type User struct &amp;#123;     id int     name,addr string     score float32 &amp;#125;  User不过是个标识符，一个指代 真正">
<meta property="og:type" content="article">
<meta property="og:title" content="Golang结构体">
<meta property="og:url" content="http://dycloudnavite.love/2023/04/17/Golang%E7%BB%93%E6%9E%84%E4%BD%93/index.html">
<meta property="og:site_name" content="J.のblog">
<meta property="og:description" content="结构体Go语言的结构体有点像面向对象语言中的”类”，但不完全是，Go语言也没打算真正实现面向对象范式 定义使用type定义结构体，可以把结构体看做类型使用。必须指定结构体的字段（属性）名称和类型。 type User struct &amp;#123;     id int     name,addr string     score float32 &amp;#125;  User不过是个标识符，一个指代 真正">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://dycloudnavite.love/img/golang.png">
<meta property="article:published_time" content="2023-04-17T06:32:00.000Z">
<meta property="article:modified_time" content="2023-08-30T02:55:27.057Z">
<meta property="article:author" content="J.">
<meta property="article:tag" content="云原生">
<meta property="article:tag" content="golang">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://dycloudnavite.love/img/golang.png"><link rel="shortcut icon" href="/dujie5416/img/touxiang.png"><link rel="canonical" href="http://dycloudnavite.love/2023/04/17/Golang%E7%BB%93%E6%9E%84%E4%BD%93/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/dujie5416/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/dujie5416/',
  algolia: {"appId":"9GWB2VV7GN","apiKey":"dac56ec5b0b1f45281251ee59db4d637","indexName":"blog","hits":{"per_page":6},"languages":{"input_placeholder":"搜索文章","hits_empty":"找不到您查询的内容：${query}","hits_stats":"找到 ${hits} 条结果，用时 ${time} 毫秒"}},
  localSearch: undefined,
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Golang结构体',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-08-30 10:55:27'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/xxx.css"><link rel="stylesheet" href="/css/universe.css"><link rel="stylesheet" href="/css/custom.css"><style type="text/css">#toggle-sidebar {bottom: 80px}</style><link rel="stylesheet" href="https://fastly.jsdelivr.net/gh/tzy13755126023/BLOG_SOURCE/css/function.min.css"><link rel="stylesheet" href="/css/rightMenu.css"><style type="text/css">#toggle-sidebar {left:100px}</style><!-- hexo injector head_end start --><link rel="stylesheet" href="https://cdn.cbd.int/hexo-butterfly-clock-anzhiyu/lib/clock.min.css" /><!-- hexo injector head_end end --><meta name="generator" content="Hexo 6.2.0"><link rel="alternate" href="/dujie5416/atom.xml" title="J.のblog" type="application/atom+xml">
</head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/dujie5416/img/touxiang.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/dujie5416/archives/"><div class="headline">文章</div><div class="length-num">73</div></a><a href="/dujie5416/tags/"><div class="headline">标签</div><div class="length-num">17</div></a><a href="/dujie5416/categories/"><div class="headline">分类</div><div class="length-num">11</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/dujie5416/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/dujie5416/img/longzhu.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/dujie5416/">J.のblog</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/dujie5416/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Golang结构体</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-04-17T06:32:00.000Z" title="发表于 2023-04-17 14:32:00">2023-04-17</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-08-30T02:55:27.057Z" title="更新于 2023-08-30 10:55:27">2023-08-30</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/dujie5416/categories/golang/">golang</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Golang结构体"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="结构体"><a href="#结构体" class="headerlink" title="结构体"></a>结构体</h1><p>Go语言的结构体有点像面向对象语言中的”类”，但不完全是，Go语言也没打算真正实现面向对象范式</p>
<h3 id="定义"><a href="#定义" class="headerlink" title="定义"></a>定义</h3><p>使用type定义结构体，可以把结构体看做类型使用。必须指定结构体的字段（属性）名称和类型。</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">type</span> User <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
    id <span class="token builtin">int</span>
    name<span class="token punctuation">,</span>addr <span class="token builtin">string</span>
    score <span class="token builtin">float32</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ul>
<li>User不过是个标识符，一个指代</li>
<li>真正的类型定义是struct{}的部分</li>
</ul>
<h3 id="初始化"><a href="#初始化" class="headerlink" title="初始化"></a>初始化</h3><pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">type</span> User <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
 id         <span class="token builtin">int</span>
 name<span class="token punctuation">,</span> addr <span class="token builtin">string</span>
 score <span class="token builtin">float32</span>
<span class="token punctuation">&#125;</span>
<span class="token comment">// 1 var声明，非常常用</span>
<span class="token keyword">var</span> u1 User <span class="token comment">// 这种方式声明结构体变量很方便，所有字段都是零值</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>u1<span class="token punctuation">)</span>
fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"%+v\n"</span><span class="token punctuation">,</span> u1<span class="token punctuation">)</span> <span class="token comment">// 加上字段打印</span>
fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"%#v\n"</span><span class="token punctuation">,</span> u1<span class="token punctuation">)</span> <span class="token comment">// 加上更多信息打印</span>
<span class="token comment">// 2 字面量初始化，推荐</span>
u2 <span class="token operator">:=</span> User<span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span> <span class="token comment">// 字段为零值</span>
fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"%#v\n"</span><span class="token punctuation">,</span> u2<span class="token punctuation">)</span>
<span class="token comment">// 3 字面量初始化，field: value为字段赋值</span>
u3 <span class="token operator">:=</span> User<span class="token punctuation">&#123;</span>id<span class="token punctuation">:</span> <span class="token number">100</span><span class="token punctuation">&#125;</span>
fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"%+v\n"</span><span class="token punctuation">,</span> u3<span class="token punctuation">)</span>
u4 <span class="token operator">:=</span> User<span class="token punctuation">&#123;</span>
 id<span class="token punctuation">:</span> <span class="token number">102</span><span class="token punctuation">,</span> score<span class="token punctuation">:</span> <span class="token number">95.8</span><span class="token punctuation">,</span>
 addr<span class="token punctuation">:</span> <span class="token string">"Nanjing"</span><span class="token punctuation">,</span> name<span class="token punctuation">:</span> <span class="token string">"Tom"</span><span class="token punctuation">,</span>
<span class="token punctuation">&#125;</span> <span class="token comment">// 名称对应无所谓顺序</span>
u5 <span class="token operator">:=</span> User<span class="token punctuation">&#123;</span><span class="token number">103</span><span class="token punctuation">,</span> <span class="token string">"John"</span><span class="token punctuation">,</span> <span class="token string">"Beijing"</span><span class="token punctuation">,</span> <span class="token number">98.5</span><span class="token punctuation">&#125;</span> <span class="token comment">// 无字段名称必须按照顺序给出全部字段值</span>
fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"%+v\n"</span><span class="token punctuation">,</span> u4<span class="token punctuation">)</span>
fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"%+v\n"</span><span class="token punctuation">,</span> u5<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="可见性"><a href="#可见性" class="headerlink" title="可见性"></a>可见性</h3><ul>
<li>Go包的顶层代码中，首字母大写的标识符，跨package包可见（导出），否则只能本包内可见</li>
<li>导出的结构体，package内外皆可见，同时，导出的结构体中的成员（属性、方法）要在包外也可见，则也需要首字母大写</li>
</ul>
<h3 id="访问"><a href="#访问" class="headerlink" title="访问"></a>访问</h3><p>可以使用字段名访问</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">u1 <span class="token operator">:=</span> User<span class="token punctuation">&#123;</span><span class="token number">103</span><span class="token punctuation">,</span> <span class="token string">"John"</span><span class="token punctuation">,</span> <span class="token string">"Beijing"</span><span class="token punctuation">,</span> <span class="token number">98.5</span><span class="token punctuation">&#125;</span> <span class="token comment">// 无字段名称必须按照顺序给出全部字段值</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>u1<span class="token punctuation">.</span>id<span class="token punctuation">,</span> u1<span class="token punctuation">.</span>name<span class="token punctuation">,</span> u1<span class="token punctuation">.</span>score<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<h3 id="修改"><a href="#修改" class="headerlink" title="修改"></a>修改</h3><p>通过字段来修改</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">u1 <span class="token operator">:=</span> User<span class="token punctuation">&#123;</span><span class="token number">103</span><span class="token punctuation">,</span> <span class="token string">"John"</span><span class="token punctuation">,</span> <span class="token string">"Beijing"</span><span class="token punctuation">,</span> <span class="token number">98.5</span><span class="token punctuation">&#125;</span> <span class="token comment">// 无字段名称必须按照顺序给出全部字段值</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>u1<span class="token punctuation">)</span>
u1<span class="token punctuation">.</span>name <span class="token operator">=</span> <span class="token string">"Tom"</span>
u1<span class="token punctuation">.</span>score <span class="token operator">=</span> <span class="token number">88</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>u1<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="成员方法"><a href="#成员方法" class="headerlink" title="成员方法"></a>成员方法</h3><p>利用下面形式为结构体组合方法</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">type</span> User <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
 id         <span class="token builtin">int</span>
 name<span class="token punctuation">,</span> addr <span class="token builtin">string</span>
 score      <span class="token builtin">float32</span>
<span class="token punctuation">&#125;</span>
<span class="token comment">// u称为receiver</span>
<span class="token comment">// 等价于 func (User) string</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>u User<span class="token punctuation">)</span> <span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">string</span> <span class="token punctuation">&#123;</span>
 <span class="token keyword">return</span> u<span class="token punctuation">.</span>name
<span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
 u1 <span class="token operator">:=</span> User<span class="token punctuation">&#123;</span><span class="token number">103</span><span class="token punctuation">,</span> <span class="token string">"John"</span><span class="token punctuation">,</span> <span class="token string">"Beijing"</span><span class="token punctuation">,</span> <span class="token number">98.5</span><span class="token punctuation">&#125;</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>u1<span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="指针"><a href="#指针" class="headerlink" title="指针"></a>指针</h3><pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">type</span> Point <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
 x<span class="token punctuation">,</span> y <span class="token builtin">int</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">var</span> p1 <span class="token operator">=</span> Point<span class="token punctuation">&#123;</span><span class="token number">10</span><span class="token punctuation">,</span> <span class="token number">20</span><span class="token punctuation">&#125;</span>        <span class="token comment">// 实例</span>
fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"%T, %[1]v\n"</span><span class="token punctuation">,</span> p1<span class="token punctuation">)</span> <span class="token comment">// Point, &#123;10, 20&#125;</span>
<span class="token keyword">var</span> p2 <span class="token operator">=</span> <span class="token operator">&amp;</span>Point<span class="token punctuation">&#123;</span><span class="token number">5</span><span class="token punctuation">,</span> <span class="token number">6</span><span class="token punctuation">&#125;</span>         <span class="token comment">// 指针</span>
fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"%T, %[1]v\n"</span><span class="token punctuation">,</span> p2<span class="token punctuation">)</span> <span class="token comment">// *Point, &amp;&#123;5, 6&#125;</span>
<span class="token keyword">var</span> p3 <span class="token operator">=</span> <span class="token function">new</span><span class="token punctuation">(</span>Point<span class="token punctuation">)</span>           <span class="token comment">// new实例化一个结构体并返回</span>
fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"%T, %[1]v\n"</span><span class="token punctuation">,</span> p3<span class="token punctuation">)</span> <span class="token comment">// *Point, &amp;&#123;0, 0&#125;</span>
<span class="token comment">// 通过实例修改属性</span>
p1<span class="token punctuation">.</span>x <span class="token operator">=</span> <span class="token number">100</span>
fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"%T, %[1]v\n"</span><span class="token punctuation">,</span> p1<span class="token punctuation">)</span> <span class="token comment">// Point, &#123;100, 20&#125;</span>
<span class="token comment">// 通过指针修改属性</span>
p2<span class="token punctuation">.</span>x <span class="token operator">=</span> <span class="token number">200</span>
p3<span class="token punctuation">.</span>x <span class="token operator">=</span> <span class="token number">300</span>
fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"%T, %[1]v\n"</span><span class="token punctuation">,</span> p2<span class="token punctuation">)</span> <span class="token comment">// *Point, &amp;&#123;200, 6&#125;</span>
fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"%T, %[1]v\n"</span><span class="token punctuation">,</span> p3<span class="token punctuation">)</span> <span class="token comment">// *Point, &amp;&#123;300, 0&#125;</span>
<span class="token comment">// p3.x中. 是 -> 的语法糖，更方便使用。等价于(*p3).x</span>
fmt<span class="token punctuation">.</span><span class="token function">Print</span><span class="token punctuation">(</span><span class="token operator">*</span>p3<span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token operator">*</span>p3<span class="token punctuation">)</span><span class="token punctuation">.</span>x<span class="token punctuation">)</span> <span class="token comment">// &#123;300 0&#125; 300</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<p>运行结果如下</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token number">1</span> <span class="token punctuation">&#123;</span>x<span class="token punctuation">:</span><span class="token number">10</span> y<span class="token punctuation">:</span><span class="token number">20</span><span class="token punctuation">&#125;</span> <span class="token number">0xc00001a0a0</span>
<span class="token number">2</span> <span class="token punctuation">&#123;</span>x<span class="token punctuation">:</span><span class="token number">10</span> y<span class="token punctuation">:</span><span class="token number">20</span><span class="token punctuation">&#125;</span> <span class="token number">0xc00001a0e0</span>
<span class="token number">3</span> <span class="token operator">&amp;</span><span class="token punctuation">&#123;</span>x<span class="token punctuation">:</span><span class="token number">10</span> y<span class="token punctuation">:</span><span class="token number">20</span><span class="token punctuation">&#125;</span> <span class="token number">0xc00001a0a0</span>
<span class="token number">4</span> <span class="token punctuation">&#123;</span><span class="token number">10</span> <span class="token number">20</span><span class="token punctuation">&#125;</span> <span class="token number">0xc00001a140</span>
<span class="token number">5</span> <span class="token punctuation">&#123;</span>x<span class="token punctuation">:</span><span class="token number">10</span> y<span class="token punctuation">:</span><span class="token number">20</span><span class="token punctuation">&#125;</span> <span class="token number">0xc00001a130</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>可以看出，结构体是非引用类型，使用的是值拷贝。传参或返回值如果使用结构体实例，将产生很多副本。如何避免过多副本，如何保证函数内外使用的是同一个结构体实例？使用指针</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">package</span> main
<span class="token keyword">import</span> <span class="token string">"fmt"</span>
<span class="token keyword">type</span> Point <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
 x<span class="token punctuation">,</span> y <span class="token builtin">int</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token function">test</span><span class="token punctuation">(</span>p <span class="token operator">*</span>Point<span class="token punctuation">)</span> <span class="token operator">*</span>Point <span class="token punctuation">&#123;</span>
 p<span class="token punctuation">.</span>x <span class="token operator">+=</span> <span class="token number">100</span>
 fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"4 %+v %p\n"</span><span class="token punctuation">,</span> p<span class="token punctuation">,</span> p<span class="token punctuation">)</span>
 <span class="token keyword">return</span> p 
<span class="token punctuation">&#125;</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>

	<span class="token keyword">var</span> p1 <span class="token operator">=</span> Point<span class="token punctuation">&#123;</span><span class="token number">10</span><span class="token punctuation">,</span> <span class="token number">20</span><span class="token punctuation">&#125;</span> <span class="token comment">// 实例</span>
	fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"1 %+v %p\n"</span><span class="token punctuation">,</span> p1<span class="token punctuation">,</span> <span class="token operator">&amp;</span>p1<span class="token punctuation">)</span>
	p2 <span class="token operator">:=</span> p1
	fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"2 %+v %p\n"</span><span class="token punctuation">,</span> p2<span class="token punctuation">,</span> <span class="token operator">&amp;</span>p2<span class="token punctuation">)</span>
	p3 <span class="token operator">:=</span> <span class="token operator">&amp;</span>p1
	fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"3 %+v %p\n"</span><span class="token punctuation">,</span> p3<span class="token punctuation">,</span> p3<span class="token punctuation">)</span>
	fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"~~~~~~~~~~~~~~~~~~~~~~~~~~~"</span><span class="token punctuation">)</span>
	p4 <span class="token operator">:=</span> <span class="token function">test</span><span class="token punctuation">(</span>p3<span class="token punctuation">)</span>
	fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"5 %+v %p\n"</span><span class="token punctuation">,</span> p1<span class="token punctuation">,</span> <span class="token operator">&amp;</span>p1<span class="token punctuation">)</span>
	fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"6 %+v %p\n"</span><span class="token punctuation">,</span> p4<span class="token punctuation">,</span> p4<span class="token punctuation">)</span>
	p4<span class="token punctuation">.</span>x <span class="token operator">+=</span> <span class="token number">200</span>
	fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"7 %+v %p\n"</span><span class="token punctuation">,</span> p1<span class="token punctuation">,</span> <span class="token operator">&amp;</span>p1<span class="token punctuation">)</span>
	fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"8 %+v %p\n"</span><span class="token punctuation">,</span> p4<span class="token punctuation">,</span> p4<span class="token punctuation">)</span>
	p5 <span class="token operator">:=</span> p3
	p5<span class="token punctuation">.</span>y <span class="token operator">=</span> <span class="token number">400</span> <span class="token comment">// 会发生什么？</span>
	fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"9 %+v %p\n"</span><span class="token punctuation">,</span> p1<span class="token punctuation">,</span> <span class="token operator">&amp;</span>p1<span class="token punctuation">)</span>
	fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"10 %+v %p\n"</span><span class="token punctuation">,</span> p4<span class="token punctuation">,</span> p4<span class="token punctuation">)</span>
	fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"11 %+v %p\n"</span><span class="token punctuation">,</span> p5<span class="token punctuation">,</span> p5<span class="token punctuation">)</span>

<span class="token punctuation">&#125;</span>
<span class="token comment">//输出</span>
<span class="token number">1</span> <span class="token punctuation">&#123;</span>x<span class="token punctuation">:</span><span class="token number">10</span> y<span class="token punctuation">:</span><span class="token number">20</span><span class="token punctuation">&#125;</span> <span class="token number">0xc00018e010</span>
<span class="token number">2</span> <span class="token punctuation">&#123;</span>x<span class="token punctuation">:</span><span class="token number">10</span> y<span class="token punctuation">:</span><span class="token number">20</span><span class="token punctuation">&#125;</span> <span class="token number">0xc00018e050</span>
<span class="token number">3</span> <span class="token operator">&amp;</span><span class="token punctuation">&#123;</span>x<span class="token punctuation">:</span><span class="token number">10</span> y<span class="token punctuation">:</span><span class="token number">20</span><span class="token punctuation">&#125;</span> <span class="token number">0xc00018e010</span>
~~~~~~~~~~~~~~~~~~~~~~~~~~~
<span class="token number">4</span> <span class="token operator">&amp;</span><span class="token punctuation">&#123;</span><span class="token number">10</span> <span class="token number">20</span><span class="token punctuation">&#125;</span> <span class="token number">0xc00018e010</span>
<span class="token number">5</span> <span class="token punctuation">&#123;</span>x<span class="token punctuation">:</span><span class="token number">10</span> y<span class="token punctuation">:</span><span class="token number">20</span><span class="token punctuation">&#125;</span> <span class="token number">0xc00018e010</span>
<span class="token number">6</span> <span class="token operator">&amp;</span><span class="token punctuation">&#123;</span>x<span class="token punctuation">:</span><span class="token number">10</span> y<span class="token punctuation">:</span><span class="token number">20</span><span class="token punctuation">&#125;</span> <span class="token number">0xc00018e010</span>
<span class="token number">7</span> <span class="token punctuation">&#123;</span>x<span class="token punctuation">:</span><span class="token number">210</span> y<span class="token punctuation">:</span><span class="token number">20</span><span class="token punctuation">&#125;</span> <span class="token number">0xc00018e010</span>
<span class="token number">8</span> <span class="token operator">&amp;</span><span class="token punctuation">&#123;</span>x<span class="token punctuation">:</span><span class="token number">210</span> y<span class="token punctuation">:</span><span class="token number">20</span><span class="token punctuation">&#125;</span> <span class="token number">0xc00018e010</span>
<span class="token number">9</span> <span class="token punctuation">&#123;</span>x<span class="token punctuation">:</span><span class="token number">210</span> y<span class="token punctuation">:</span><span class="token number">400</span><span class="token punctuation">&#125;</span> <span class="token number">0xc00018e010</span>
<span class="token number">10</span> <span class="token operator">&amp;</span><span class="token punctuation">&#123;</span>x<span class="token punctuation">:</span><span class="token number">210</span> y<span class="token punctuation">:</span><span class="token number">400</span><span class="token punctuation">&#125;</span> <span class="token number">0xc00018e010</span>
<span class="token number">11</span> <span class="token operator">&amp;</span><span class="token punctuation">&#123;</span>x<span class="token punctuation">:</span><span class="token number">210</span> y<span class="token punctuation">:</span><span class="token number">400</span><span class="token punctuation">&#125;</span> <span class="token number">0xc00018e010</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>说明，使用了同一个内存区域中的结构体实例，减少了拷贝</p>
<h5 id="匿名结构体"><a href="#匿名结构体" class="headerlink" title="匿名结构体"></a>匿名结构体</h5><p>匿名结构体：标识符直接使用struct部分结构体本身来作为类型，而不是使用type定义的有名字的结构体的标识符。</p>
<p>可以使用<code>var</code>、<code>const</code>、<code>:= </code>来定义匿名结构体</p>
<p>type定义结构体的标识符，可以反复定义其结构体实例，但是匿名结构体是一次性的。</p>
<p><img src="/images/QzaKfUq0IZSFi0iI45-KHuXLjXsmCfrTExRYt2Qucoc.png" alt="image"></p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">var</span> Point <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
 x<span class="token punctuation">,</span> y <span class="token builtin">int</span>
<span class="token punctuation">&#125;</span> <span class="token comment">// 定义Point是后面匿名结构体类型的，用零值</span>
fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"%#v\n"</span><span class="token punctuation">,</span> Point<span class="token punctuation">)</span> <span class="token comment">// 得到的是一个结构体实例</span>
<span class="token keyword">var</span> message <span class="token operator">=</span> <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
 id   <span class="token builtin">int</span>
 data <span class="token builtin">string</span>
<span class="token punctuation">&#125;</span><span class="token punctuation">&#123;</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token string">"OK"</span><span class="token punctuation">&#125;</span> <span class="token comment">// 不用零值，初始化</span>
fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"%#v\n"</span><span class="token punctuation">,</span> message<span class="token punctuation">)</span>
student <span class="token operator">:=</span> <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
 id   <span class="token builtin">int</span>
 name <span class="token builtin">string</span>
<span class="token punctuation">&#125;</span><span class="token punctuation">&#123;</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token string">"Tom"</span><span class="token punctuation">&#125;</span> <span class="token comment">// 短格式定义并初始化</span>
fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"%#v\n"</span><span class="token punctuation">,</span> student<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>匿名结构体，只是为了快速方便地得到一个结构体实例，而不是使用结构体创建N个实例。</p>
<h5 id="匿名成员"><a href="#匿名成员" class="headerlink" title="匿名成员"></a>匿名成员</h5><p>有时候属性名可以省略</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">type</span> Point <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
 x    <span class="token builtin">int</span>
 <span class="token builtin">int</span>  <span class="token comment">// 字段，匿名成员变量</span>
 <span class="token builtin">bool</span> <span class="token comment">// 匿名，必须类型不一样才能区分</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">var</span> p1 <span class="token operator">=</span> Point<span class="token punctuation">&#123;</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token boolean">false</span><span class="token punctuation">&#125;</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>p1<span class="token punctuation">)</span>
<span class="token keyword">var</span> p2 <span class="token operator">=</span> Point<span class="token punctuation">&#123;</span>x<span class="token punctuation">:</span> <span class="token number">20</span><span class="token punctuation">,</span> <span class="token builtin">int</span><span class="token punctuation">:</span> <span class="token number">5</span><span class="token punctuation">,</span> <span class="token builtin">bool</span><span class="token punctuation">:</span> <span class="token boolean">false</span><span class="token punctuation">&#125;</span> <span class="token comment">// 使用类型名作为字段名</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>p2<span class="token punctuation">,</span> p1<span class="token punctuation">.</span>x<span class="token punctuation">,</span> p2<span class="token punctuation">.</span><span class="token builtin">int</span><span class="token punctuation">,</span> p2<span class="token punctuation">.</span><span class="token builtin">bool</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<h5 id="构造函数"><a href="#构造函数" class="headerlink" title="构造函数"></a>构造函数</h5><p>Go语言并没有从语言层面为结构体提供什么构造器，但是有时候可以通过一个函数为结构体初始化提供属性值，从而方便得到一个结构体实例。习惯上，函数命名为<code>Newxxx</code>的形式</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">package</span> main
<span class="token keyword">import</span> <span class="token string">"fmt"</span>
<span class="token keyword">type</span> Animal <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
 name <span class="token builtin">string</span>
 age  <span class="token builtin">int</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token function">NewAnimal</span><span class="token punctuation">(</span>name <span class="token builtin">string</span><span class="token punctuation">,</span> age <span class="token builtin">int</span><span class="token punctuation">)</span> Animal <span class="token punctuation">&#123;</span>
 a <span class="token operator">:=</span> Animal<span class="token punctuation">&#123;</span>name<span class="token punctuation">,</span> age<span class="token punctuation">&#125;</span>
 fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"%+v, %p\n"</span><span class="token punctuation">,</span> a<span class="token punctuation">,</span> <span class="token operator">&amp;</span>a<span class="token punctuation">)</span>
 <span class="token keyword">return</span> a 
<span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
 a <span class="token operator">:=</span> <span class="token function">NewAnimal</span><span class="token punctuation">(</span><span class="token string">"Tom"</span><span class="token punctuation">,</span> <span class="token number">20</span><span class="token punctuation">)</span>
 fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"%+v, %p\n"</span><span class="token punctuation">,</span> a<span class="token punctuation">,</span> <span class="token operator">&amp;</span>a<span class="token punctuation">)</span> 
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<h5 id="父子关系构造"><a href="#父子关系构造" class="headerlink" title="父子关系构造"></a>父子关系构造</h5><p>动物类包括猫类，猫属于猫类，猫也属于动物类，某动物一定是动物类，但不能说某动物一定是猫类。</p>
<p>将上例中的Animal结构体，使用匿名成员的方式，嵌入到Cat结构体中，看看效果</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">package</span> main
<span class="token keyword">import</span> <span class="token string">"fmt"</span>
<span class="token keyword">type</span> Animal <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
 name <span class="token builtin">string</span>
 age  <span class="token builtin">int</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">type</span> Cat <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
 Animal <span class="token comment">// 匿名成员，可以使用类型名作为访问的属性名</span>
 color  <span class="token builtin">string</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
 <span class="token keyword">var</span> cat <span class="token operator">=</span> <span class="token function">new</span><span class="token punctuation">(</span>Cat<span class="token punctuation">)</span> <span class="token comment">// Cat实例化，Animal同时被实例化</span>
 fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"%#v\n"</span><span class="token punctuation">,</span> cat<span class="token punctuation">)</span>
 cat<span class="token punctuation">.</span>color <span class="token operator">=</span> <span class="token string">"black"</span>     <span class="token comment">// 子结构体属性</span>
 cat<span class="token punctuation">.</span>Animal<span class="token punctuation">.</span>name <span class="token operator">=</span> <span class="token string">"Tom"</span> <span class="token comment">// 完整属性访问</span>
 cat<span class="token punctuation">.</span>age <span class="token operator">=</span> <span class="token number">20</span>            <span class="token comment">// 简化写法，只有匿名成员才有这种效果</span>
 fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"%#v\n"</span><span class="token punctuation">,</span> cat<span class="token punctuation">)</span> 
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<ul>
<li>使用结构体嵌套实现类似面向对象父类子类继承（派生）的效果</li>
<li>子结构体使用匿名成员能简化调用父结构体成员</li>
</ul>
<h5 id="指针类型receiver"><a href="#指针类型receiver" class="headerlink" title="指针类型receiver"></a>指针类型receiver</h5><p>Go语言，可以为任意类型包括结构体增加方法，形式是<code>func Receiver 方法名 签名 &#123;函数体&#125; </code> 这个receiver类似其他语言中的this或self</p>
<p>receiver必须是一个类型T实例或类型T的指针，T不能是指针或接口</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">package</span> main
<span class="token keyword">import</span> <span class="token string">"fmt"</span>
<span class="token keyword">type</span> Point <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
 x<span class="token punctuation">,</span> y <span class="token builtin">int</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>p Point<span class="token punctuation">)</span> <span class="token function">getX</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">int</span> <span class="token punctuation">&#123;</span> <span class="token comment">// getX方法绑定到结构体类型Point</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"instance"</span><span class="token punctuation">)</span>
 <span class="token keyword">return</span> p<span class="token punctuation">.</span>x 
<span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>p <span class="token operator">*</span>Point<span class="token punctuation">)</span> <span class="token function">getY</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">int</span> <span class="token punctuation">&#123;</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"pointer"</span><span class="token punctuation">)</span>
 <span class="token keyword">return</span> p<span class="token punctuation">.</span>y <span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
 p <span class="token operator">:=</span> Point<span class="token punctuation">&#123;</span><span class="token number">4</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">&#125;</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>p<span class="token punctuation">)</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>p<span class="token punctuation">.</span><span class="token function">getX</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token operator">&amp;</span>p<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getX</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"~~~~~~~~~~~~~~~~~~~~~~~~~~~"</span><span class="token punctuation">)</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>p<span class="token punctuation">.</span><span class="token function">getY</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token operator">&amp;</span>p<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getY</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>运行结果如下</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token punctuation">&#123;</span><span class="token number">4</span> <span class="token number">5</span><span class="token punctuation">&#125;</span>
instance
instance
<span class="token number">4</span> <span class="token number">4</span>
~~~~~~~~~~~~~~~~~~~~~~~~~~~
pointer
pointer
<span class="token number">5</span> <span class="token number">5</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>如果方法中不使用receiver，其标识符可以省略</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">func</span> <span class="token punctuation">(</span>Point<span class="token punctuation">)</span> <span class="token function">Comment</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"这是个点"</span><span class="token punctuation">)</span> 
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>


<p>接收器receiver可以是类型T也可以是指针*T，定义的方法有什么区别？</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">package</span> main
<span class="token keyword">import</span> <span class="token string">"fmt"</span>
<span class="token keyword">type</span> Point <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
 x<span class="token punctuation">,</span> y <span class="token builtin">int</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>p Point<span class="token punctuation">)</span> <span class="token function">getX</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">int</span> <span class="token punctuation">&#123;</span>
 <span class="token keyword">return</span> p<span class="token punctuation">.</span>x
 <span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>p <span class="token operator">*</span>Point<span class="token punctuation">)</span> <span class="token function">getY</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">int</span> <span class="token punctuation">&#123;</span>
 <span class="token keyword">return</span> p<span class="token punctuation">.</span>y 
<span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>p Point<span class="token punctuation">)</span> <span class="token function">setX</span><span class="token punctuation">(</span>v <span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
 fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"1 %+v, %p\n"</span><span class="token punctuation">,</span> p<span class="token punctuation">,</span> <span class="token operator">&amp;</span>p<span class="token punctuation">)</span>
 p<span class="token punctuation">.</span>x <span class="token operator">=</span> v
 fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"2 %+v, %p\n"</span><span class="token punctuation">,</span> p<span class="token punctuation">,</span> <span class="token operator">&amp;</span>p<span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>p <span class="token operator">*</span>Point<span class="token punctuation">)</span> <span class="token function">setY</span><span class="token punctuation">(</span>v <span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
 fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"3 %+v, %p\n"</span><span class="token punctuation">,</span> p<span class="token punctuation">,</span> p<span class="token punctuation">)</span>
 p<span class="token punctuation">.</span>y <span class="token operator">=</span> v
 fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"4 %+v, %p\n"</span><span class="token punctuation">,</span> p<span class="token punctuation">,</span> p<span class="token punctuation">)</span>
 <span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
 p <span class="token operator">:=</span> Point<span class="token punctuation">&#123;</span><span class="token number">4</span><span class="token punctuation">,</span> <span class="token number">5</span>
<span class="token punctuation">&#125;</span>
 fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"5 %+v, %p\n"</span><span class="token punctuation">,</span> p<span class="token punctuation">,</span> <span class="token operator">&amp;</span>p<span class="token punctuation">)</span>
 p<span class="token punctuation">.</span><span class="token function">setX</span><span class="token punctuation">(</span><span class="token number">11</span><span class="token punctuation">)</span> <span class="token comment">// 实例调用是值拷贝</span>
 p<span class="token punctuation">.</span><span class="token function">setY</span><span class="token punctuation">(</span><span class="token number">22</span><span class="token punctuation">)</span> <span class="token comment">// 看似实例调用，实则是指针，操作同一处内存</span>
 fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"6 %+v, %p\n"</span><span class="token punctuation">,</span> p<span class="token punctuation">,</span> <span class="token operator">&amp;</span>p<span class="token punctuation">)</span> 
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token punctuation">&#123;</span>x<span class="token punctuation">:</span><span class="token number">4</span> y<span class="token punctuation">:</span><span class="token number">5</span><span class="token punctuation">&#125;</span><span class="token punctuation">,</span> <span class="token number">0xc000128070</span>
<span class="token punctuation">&#123;</span>x<span class="token punctuation">:</span><span class="token number">4</span> y<span class="token punctuation">:</span><span class="token number">5</span><span class="token punctuation">&#125;</span><span class="token punctuation">,</span> <span class="token number">0xc0001280c0</span>
<span class="token punctuation">&#123;</span>x<span class="token punctuation">:</span><span class="token number">11</span> y<span class="token punctuation">:</span><span class="token number">5</span><span class="token punctuation">&#125;</span><span class="token punctuation">,</span> <span class="token number">0xc0001280c0</span>
<span class="token operator">&amp;</span><span class="token punctuation">&#123;</span>x<span class="token punctuation">:</span><span class="token number">4</span> y<span class="token punctuation">:</span><span class="token number">5</span><span class="token punctuation">&#125;</span><span class="token punctuation">,</span> <span class="token number">0xc000128070</span>
<span class="token operator">&amp;</span><span class="token punctuation">&#123;</span>x<span class="token punctuation">:</span><span class="token number">4</span> y<span class="token punctuation">:</span><span class="token number">22</span><span class="token punctuation">&#125;</span><span class="token punctuation">,</span> <span class="token number">0xc000128070</span>
<span class="token punctuation">&#123;</span>x<span class="token punctuation">:</span><span class="token number">4</span> y<span class="token punctuation">:</span><span class="token number">22</span><span class="token punctuation">&#125;</span><span class="token punctuation">,</span> <span class="token number">0xc000128070</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<p>非常明显，如果是非指针接收器方法调用有值拷贝，操作的是副本，而指针接收器方法调用操作的是同一个内存的同一个实例。</p>
<p>如果是操作大内存对象时，且操作同一个实例时，一定要采用指针接收器的方法。</p>
<h5 id="深浅拷贝"><a href="#深浅拷贝" class="headerlink" title="深浅拷贝"></a>深浅拷贝</h5><ul>
<li>shadow copy<ul>
<li>影子拷贝，也叫浅拷贝。遇到引用类型数据，仅仅复制一个引用而已</li>
</ul>
</li>
<li>deep copy<ul>
<li>深拷贝，往往会递归复制一定深度</li>
</ul>
</li>
</ul>
<p>注意，深浅拷贝说的是拷贝过程中是否发生递归拷贝，也就是说如果某个值是一个地址，是只复制这个地址 ，还是复制地址指向的内容。</p>
<p>值拷贝是深拷贝，地址拷贝是浅拷贝，这种说法是错误的。因为地址拷贝只是拷贝了地址，因此本质上来讲也是值拷贝。</p>
<p>Go语言中，引用类型实际上拷贝的是标头值，这也是值拷贝，并没有通过标头值中对底层数据结构的指针指向的内容进行复制，这就是浅拷贝。非引用类型的复制就是值拷贝，也就是再造一个副本，这也是浅拷贝。因为你不能说对一个整数值在内存中复制出一个副本，就是深的拷贝。像整数类型这样的基本类型就是一个单独的值，没法深入拷贝，根本没法去讲深入的事儿。</p>
<p>简单讲，大家可以用拷贝文件是否对软链接跟进来理解。直接复制软链接就是浅拷贝，钻进软链接里面复制其内容就是深拷贝。</p>
<p>复杂数据结构，往往会有嵌套，有时嵌套很深，如果都采用深拷贝，那代价很高，所以，浅拷贝才是语言普遍采用的方案。</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="http://dycloudnavite.love">J.</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://dycloudnavite.love/2023/04/17/Golang%E7%BB%93%E6%9E%84%E4%BD%93/">http://dycloudnavite.love/2023/04/17/Golang%E7%BB%93%E6%9E%84%E4%BD%93/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://dycloudnavite.love" target="_blank">J.のblog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/dujie5416/tags/%E4%BA%91%E5%8E%9F%E7%94%9F/">云原生</a><a class="post-meta__tags" href="/dujie5416/tags/golang/">golang</a></div><div class="post_share"><div class="addthis_inline_share_toolbox"></div><script src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-5d034d84b42927bf" async="async"></script></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/dujie5416/img/wechat.jpg" target="_blank"><img class="post-qr-code-img" src="/dujie5416/img/wechat.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="/dujie5416/img/alipay.jpg" target="_blank"><img class="post-qr-code-img" src="/dujie5416/img/alipay.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/dujie5416/2023/04/17/Golang%E5%8F%98%E9%87%8F%E9%80%83%E9%80%B8%E2%80%94%E2%80%94%E5%A0%86%E3%80%81%E6%A0%88/"><img class="prev-cover" src="/dujie5416/img/golang.png" onerror="onerror=null;src='/dujie5416/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Golang变量逃逸————堆、栈</div></div></a></div><div class="next-post pull-right"><a href="/dujie5416/2023/04/16/Golang%E9%80%92%E5%BD%92%E3%80%81%E5%8C%BF%E5%90%8D%E5%87%BD%E6%95%B0%E3%80%81%E4%BD%9C%E7%94%A8%E5%9F%9F%E3%80%81%E9%97%AD%E5%8C%85/"><img class="next-cover" src="/dujie5416/img/golang.png" onerror="onerror=null;src='/dujie5416/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Golang递归、匿名函数、作用域、闭包</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/dujie5416/2023/05/20/Channel%E9%80%9A%E9%81%93/" title="Channel通道"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-05-20</div><div class="title">Channel通道</div></div></a></div><div><a href="/dujie5416/2023/05/06/Golang%E4%B8%AD%E7%9A%84GORM/" title="Golang GORM使用"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-05-06</div><div class="title">Golang GORM使用</div></div></a></div><div><a href="/dujie5416/2023/06/23/Gin%E6%A1%86%E6%9E%B6/" title="Gin框架"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-06-23</div><div class="title">Gin框架</div></div></a></div><div><a href="/dujie5416/2023/05/15/Golang%E5%8D%8F%E7%A8%8B/" title="Golang协程"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-05-15</div><div class="title">Golang协程</div></div></a></div><div><a href="/dujie5416/2023/04/17/Golang%E5%8F%98%E9%87%8F%E9%80%83%E9%80%B8%E2%80%94%E2%80%94%E5%A0%86%E3%80%81%E6%A0%88/" title="Golang变量逃逸————堆、栈"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-04-17</div><div class="title">Golang变量逃逸————堆、栈</div></div></a></div><div><a href="/dujie5416/2023/02/13/Golang%E5%AD%97%E7%AC%A6%E4%B8%B2string/" title="Golang字符串"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-02-13</div><div class="title">Golang字符串</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="lv-container" data-id="city" data-uid="MTAyMC81Njk5OS8zMzQ2Mw=="></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/dujie5416/img/touxiang.png" onerror="this.onerror=null;this.src='/dujie5416/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">J.</div><div class="author-info__description"></div></div><div class="card-info-data site-data is-center"><a href="/dujie5416/archives/"><div class="headline">文章</div><div class="length-num">73</div></a><a href="/dujie5416/tags/"><div class="headline">标签</div><div class="length-num">17</div></a><a href="/dujie5416/categories/"><div class="headline">分类</div><div class="length-num">11</div></a></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%BB%93%E6%9E%84%E4%BD%93"><span class="toc-number">1.</span> <span class="toc-text">结构体</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AE%9A%E4%B9%89"><span class="toc-number">1.0.1.</span> <span class="toc-text">定义</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%88%9D%E5%A7%8B%E5%8C%96"><span class="toc-number">1.0.2.</span> <span class="toc-text">初始化</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8F%AF%E8%A7%81%E6%80%A7"><span class="toc-number">1.0.3.</span> <span class="toc-text">可见性</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%AE%BF%E9%97%AE"><span class="toc-number">1.0.4.</span> <span class="toc-text">访问</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BF%AE%E6%94%B9"><span class="toc-number">1.0.5.</span> <span class="toc-text">修改</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%88%90%E5%91%98%E6%96%B9%E6%B3%95"><span class="toc-number">1.0.6.</span> <span class="toc-text">成员方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%8C%87%E9%92%88"><span class="toc-number">1.0.7.</span> <span class="toc-text">指针</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%8C%BF%E5%90%8D%E7%BB%93%E6%9E%84%E4%BD%93"><span class="toc-number">1.0.7.0.1.</span> <span class="toc-text">匿名结构体</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%8C%BF%E5%90%8D%E6%88%90%E5%91%98"><span class="toc-number">1.0.7.0.2.</span> <span class="toc-text">匿名成员</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0"><span class="toc-number">1.0.7.0.3.</span> <span class="toc-text">构造函数</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E7%88%B6%E5%AD%90%E5%85%B3%E7%B3%BB%E6%9E%84%E9%80%A0"><span class="toc-number">1.0.7.0.4.</span> <span class="toc-text">父子关系构造</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%8C%87%E9%92%88%E7%B1%BB%E5%9E%8Breceiver"><span class="toc-number">1.0.7.0.5.</span> <span class="toc-text">指针类型receiver</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%B7%B1%E6%B5%85%E6%8B%B7%E8%B4%9D"><span class="toc-number">1.0.7.0.6.</span> <span class="toc-text">深浅拷贝</span></a></li></ol></li></ol></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/dujie5416/2023/07/29/%E6%A0%B9%E6%8D%AErouter%E6%98%BE%E7%A4%BA%E5%B7%A6%E4%BE%A7%E8%8F%9C%E5%8D%95%E6%A0%8F%E9%9A%90%E8%97%8F%E6%9F%90%E4%B8%AA%E8%8F%9C%E5%8D%95%E9%80%89%E9%A1%B9/" title="vue3左侧菜单隐藏某选项"><img src="/dujie5416/img/golang.png" onerror="this.onerror=null;this.src='/dujie5416/img/404.jpg'" alt="vue3左侧菜单隐藏某选项"/></a><div class="content"><a class="title" href="/dujie5416/2023/07/29/%E6%A0%B9%E6%8D%AErouter%E6%98%BE%E7%A4%BA%E5%B7%A6%E4%BE%A7%E8%8F%9C%E5%8D%95%E6%A0%8F%E9%9A%90%E8%97%8F%E6%9F%90%E4%B8%AA%E8%8F%9C%E5%8D%95%E9%80%89%E9%A1%B9/" title="vue3左侧菜单隐藏某选项">vue3左侧菜单隐藏某选项</a><time datetime="2023-07-29T06:32:00.000Z" title="发表于 2023-07-29 14:32:00">2023-07-29</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/dujie5416/2023/07/13/Vue%E7%8A%B6%E6%80%81%E7%AE%A1%E7%90%86/" title="Vue状态管理"><img src="/dujie5416/img/golang.png" onerror="this.onerror=null;this.src='/dujie5416/img/404.jpg'" alt="Vue状态管理"/></a><div class="content"><a class="title" href="/dujie5416/2023/07/13/Vue%E7%8A%B6%E6%80%81%E7%AE%A1%E7%90%86/" title="Vue状态管理">Vue状态管理</a><time datetime="2023-07-13T09:29:00.000Z" title="发表于 2023-07-13 17:29:00">2023-07-13</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/dujie5416/2023/06/27/%E5%9F%BA%E4%BA%8EIOC%E8%A7%A3%E5%86%B3%E5%AF%B9%E8%B1%A1%E4%BE%9D%E8%B5%96%E9%97%AE%E9%A2%98/" title="基于IOC解决对象依赖问题"><img src="/dujie5416/img/golang.png" onerror="this.onerror=null;this.src='/dujie5416/img/404.jpg'" alt="基于IOC解决对象依赖问题"/></a><div class="content"><a class="title" href="/dujie5416/2023/06/27/%E5%9F%BA%E4%BA%8EIOC%E8%A7%A3%E5%86%B3%E5%AF%B9%E8%B1%A1%E4%BE%9D%E8%B5%96%E9%97%AE%E9%A2%98/" title="基于IOC解决对象依赖问题">基于IOC解决对象依赖问题</a><time datetime="2023-06-27T03:32:00.000Z" title="发表于 2023-06-27 11:32:00">2023-06-27</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/dujie5416/2023/06/23/Gin%E6%A1%86%E6%9E%B6/" title="Gin框架"><img src="/dujie5416/img/golang.png" onerror="this.onerror=null;this.src='/dujie5416/img/404.jpg'" alt="Gin框架"/></a><div class="content"><a class="title" href="/dujie5416/2023/06/23/Gin%E6%A1%86%E6%9E%B6/" title="Gin框架">Gin框架</a><time datetime="2023-06-23T06:32:00.000Z" title="发表于 2023-06-23 14:32:00">2023-06-23</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/dujie5416/2023/06/04/ServeMux%E3%80%81httprouter/" title="ServeMux、httprouter"><img src="/dujie5416/img/golang.png" onerror="this.onerror=null;this.src='/dujie5416/img/404.jpg'" alt="ServeMux、httprouter"/></a><div class="content"><a class="title" href="/dujie5416/2023/06/04/ServeMux%E3%80%81httprouter/" title="ServeMux、httprouter">ServeMux、httprouter</a><time datetime="2023-06-04T03:32:00.000Z" title="发表于 2023-06-04 11:32:00">2023-06-04</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('/dujie5416/img/longzhu.png')"><div id="footer-wrap"><div class="copyright">&copy;2019 - 2024  <i id="heartbeat" class="fa fas fa-heartbeat"></i> J.</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a><a href="http://beian.miit.gov.cn/"  style="color:#f72b07" target="_blank">京ICP备2022023567号</a></div></div><link rel="stylesheet" href="https://fastly.jsdelivr.net/gh/HCLonely/images@master/others/heartbeat.min.css"></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="algolia-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="search-wrap"><div id="algolia-search-input"></div><hr/><div id="algolia-search-results"><div id="algolia-hits"></div><div id="algolia-pagination"></div><div id="algolia-info"><div class="algolia-stats"></div><div class="algolia-poweredBy"></div></div></div></div></div><div id="search-mask"></div></div><div id="rightMenu"><div class="rightMenu-group rightMenu-small"><div class="rightMenu-item" id="menu-backward"><i class="fa-solid fa-arrow-left"></i></div><div class="rightMenu-item" id="menu-forward"><i class="fa-solid fa-arrow-right"></i></div><div class="rightMenu-item" id="menu-refresh"><i class="fa-solid fa-arrow-rotate-right"></i></div><div class="rightMenu-item" id="menu-home"><i class="fa-solid fa-house"></i></div></div><div class="rightMenu-group rightMenu-line rightMenuOther"><a class="rightMenu-item menu-link" href="/archives/"><i class="fa-solid fa-archive"></i><span>文章归档</span></a><a class="rightMenu-item menu-link" href="/categories/"><i class="fa-solid fa-folder-open"></i><span>文章分类</span></a><a class="rightMenu-item menu-link" href="/tags/"><i class="fa-solid fa-tags"></i><span>文章标签</span></a></div><div class="rightMenu-group rightMenu-line rightMenuNormal"><a class="rightMenu-item menu-link" id="menu-radompage" href="/random/index.html"><i class="fa-solid fa-shoe-prints"></i><span>随便逛逛</span></a><div class="rightMenu-item" id="menu-translate"><i class="fa-solid fa-earth-asia"></i><span>繁简切换</span></div><div class="rightMenu-item" id="menu-darkmode"><i class="fa-solid fa-moon"></i><span>切换模式</span></div></div></div><div id="rightmenu-mask"></div><div><script src="/dujie5416/js/utils.js"></script><script src="/dujie5416/js/main.js"></script><script src="/dujie5416/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/algoliasearch/dist/algoliasearch-lite.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instantsearch.js/dist/instantsearch.production.min.js"></script><script src="/dujie5416/js/search/algolia.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"><script>function loadLivere () {
  if (typeof LivereTower === 'object') {
    window.LivereTower.init()
  }
  else {
    (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
    })(document, 'script');
  }
}

if ('Livere' === 'Livere' || !false) {
  if (false) btf.loadComment(document.getElementById('lv-container'), loadLivere)
  else loadLivere()
}
else {
  function loadOtherComment () {
    loadLivere()
  }
}</script></div><script defer src="https://npm.elemecdn.com/jquery@latest/dist/jquery.min.js"></script><script data-pjax defer src="https://npm.elemecdn.com/tzy-blog/lib/js/theme/chocolate.js"></script><canvas id="universe"></canvas><script defer src="/js/universe.js"></script><script defer data-pjax src="/js/rightMenu.js"></script><div class="aplayer no-destroy" data-id="7427714271" data-server="netease" data-type="playlist" data-fixed="true" data-mini="true" data-listFolded="false" data-order="random" data-lrctype="1" data-preload="none" data-autoplay="true" muted></div><script id="click-show-text" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/click-show-text.min.js" data-mobile="false" data-text="I,LOVE,YOU" data-fontsize="15px" data-random="false" async="async"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/metingjs/dist/Meting.min.js"></script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>let pjaxSelectors = ["meta[property=\"og:image\"]","meta[property=\"og:title\"]","meta[property=\"og:url\"]","head > title","#config-diff","#body-wrap","#rightside-config-hide","#rightside-config-show",".js-pjax"]

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.tocScrollFn && window.removeEventListener('scroll', window.tocScrollFn)
  window.scrollCollect && window.removeEventListener('scroll', scrollCollect)

  typeof preloader === 'object' && preloader.initLoading()
  document.getElementById('rightside').style.cssText = "opacity: ''; transform: ''"
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

  typeof disqusjs === 'object' && disqusjs.destroy()
})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><!-- hexo injector body_end start --><script data-pjax>
  function butterfly_clock_anzhiyu_injector_config(){
    var parent_div_git = document.getElementsByClassName('sticky_layout')[0];
    var item_html = '<div class="card-widget card-clock"><div class="card-glass"><div class="card-background"><div class="card-content"><div id="hexo_electric_clock"><img class="entered loading" id="card-clock-loading" src="https://cdn.cbd.int/hexo-butterfly-clock-anzhiyu/lib/loading.gif" style="height: 120px; width: 100%;" data-ll-status="loading"/></div></div></div></div></div>';
    console.log('已挂载butterfly_clock_anzhiyu')
    if(parent_div_git) {
      parent_div_git.insertAdjacentHTML("afterbegin",item_html)
    }
  }
  var elist = 'null'.split(',');
  var cpage = location.pathname;
  var epage = 'all';
  var qweather_key = '56289903f0d448dfbe8262dba0175f70';
  var gaud_map_key = '01603f2b2d08d0e947bb101e9d9b148b';
  var baidu_ak_key = 'undefined';
  var flag = 0;
  var clock_rectangle = '112.982279,28.19409';
  var clock_default_rectangle_enable = 'false';

  for (var i=0;i<elist.length;i++){
    if (cpage.includes(elist[i])){
      flag++;
    }
  }

  if ((epage ==='all')&&(flag == 0)){
    butterfly_clock_anzhiyu_injector_config();
  }
  else if (epage === cpage){
    butterfly_clock_anzhiyu_injector_config();
  }
  </script><script src="https://widget.qweather.net/simple/static/js/he-simple-common.js?v=2.0"></script><script data-pjax src="https://cdn.cbd.int/hexo-butterfly-clock-anzhiyu/lib/clock.min.js"></script><!-- hexo injector body_end end --><script src="/dujie5416/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"tagMode":false,"debug":false,"model":{"jsonPath":"/dujie5416/live2dw/assets/tororo.model.json"},"display":{"position":"right","width":150,"height":350,"hOffset":20,"vOffset":-20},"mobile":{"show":false},"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/"});</script><script async>window.onload=function(){var a=document.createElement('script'),b=document.getElementsByTagName('script')[0];a.type='text/javascript',a.async=!0,a.src='/sw-register.js?v='+Date.now(),b.parentNode.insertBefore(a,b)};</script></body></html>